package com.htwy.core.config;

import com.htwy.core.handler.StaticResourceHandler;
import com.htwy.ext.IMappingKit;
import com.htwy.ext.SqlSetDirective;
import com.htwy.ext.SqlWhereDirective;
import com.jfinal.config.*;
import com.jfinal.core.JFinal;
import com.jfinal.ext.plugin.shiro.ShiroInterceptor;
import com.jfinal.ext.plugin.shiro.ShiroMethod;
import com.jfinal.ext.plugin.shiro.ShiroPlugin;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.template.Engine;
import com.jfinal.template.source.ClassPathSourceFactory;

public class WebappConfig extends JFinalConfig {

    private static Prop config = PropKit.use("config.properties");
    private static Routes routes = null;

    public static boolean isUseEhcache(){
        return config.getBoolean("useEhcache",false);
    }

    public static boolean isUseDb(){
        return config.getBoolean("useDb",false);
    }

    public static boolean isUseShiro(){
        return config.getBoolean("useShiro",false);
    }

    public static String getOrgSplit() { return config.get("orgSplit","#"); }

    public static Prop getConfig(){
        return config;
    }

    @Override
    public void configConstant(Constants me) {
        me.setDevMode(config.getBoolean("devMode",false));
        me.setUrlParaSeparator("_");
        me.setBaseUploadPath(PropKit.get("upload_path", "upload"));
        me.setBaseDownloadPath(PropKit.get("upload_path", "upload"));
    }

    @Override
    public void configRoute(Routes me) {
        this.routes = me;
        //***********页面相关************
        String routeClassNames = config.get("routes");
        if(StrKit.notBlank(routeClassNames)){
            for(String routeClassName : routeClassNames.trim().split(",")){
                try {
                    try {
                        Routes routes = (Routes) Class.forName(routeClassName.trim()).newInstance();
                        me.add(routes);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void configEngine(Engine me) {
        me.setDevMode(config.getBoolean("devMode",false));
        me.setBaseTemplatePath(null);
        me.setSourceFactory(new ClassPathSourceFactory());
        me.addSharedObject("CTX", JFinal.me().getContextPath());


        if(isUseShiro()){
            me.addSharedStaticMethod(ShiroMethod.class);
        }
    }

    @Override
    public void configPlugin(Plugins me) {
        //数据库连接配置
        if(isUseDb()) {
            DruidPlugin druidPlugin = createDruidPlugin();
            me.add(druidPlugin);

            ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
            arp.setShowSql(config.getBoolean("showSql",false));
            arp.setDialect(new MysqlDialect());
            arp.getEngine().addDirective("WHERE", SqlWhereDirective.class);
            arp.getEngine().addDirective("SET", SqlSetDirective.class);

            String mappings = config.get("mappings");
            if(StrKit.notBlank(mappings)){
                for(String mapping : mappings.trim().split(",")){
                    try {
                        try {
                            IMappingKit mappingKit = (IMappingKit) Class.forName(mapping.trim()).newInstance();
                            mappingKit.mapping(arp);
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

            me.add(arp);
        }
        if(isUseShiro()){
            ShiroPlugin shiroPlugin = new ShiroPlugin(routes);
            shiroPlugin.setLoginUrl("/security/login");
            shiroPlugin.setSuccessUrl("/");
            shiroPlugin.setUnauthorizedUrl("/security/needPermission");
            me.add(shiroPlugin);
        }
        if(isUseEhcache()){
            me.add(new EhCachePlugin());
        }
    }

    /**
     * 创建数据库连接插件
     * @return druid的插件
     */
    public static DruidPlugin createDruidPlugin() {
        DruidPlugin druidPlugin = new DruidPlugin(config.get("jdbcUrl"), config.get("dbAccount"), config.get("dbPwd"), config.get("dbDriver","com.mysql.jdbc.Driver"));
        druidPlugin.setInitialSize(3);
        druidPlugin.setMinIdle(3);
        druidPlugin.setMaxActive(15);
        druidPlugin.setRemoveAbandoned(true);
        druidPlugin.setRemoveAbandonedTimeoutMillis(10 * 1000);
        druidPlugin.setTestWhileIdle(true);
        druidPlugin.setTestOnBorrow(false);
        druidPlugin.setTestOnReturn(false);
        druidPlugin.setTimeBetweenEvictionRunsMillis(10000);
        druidPlugin.setMinEvictableIdleTimeMillis(30000);
        druidPlugin.setValidationQuery("select 1 from dual");
        druidPlugin.setTimeBetweenEvictionRunsMillis(10000);
        return druidPlugin;
    }

    @Override
    public void configInterceptor(Interceptors me) {
        if(isUseShiro()){
            me.add(new ShiroInterceptor());
        }
    }

    @Override
    public void configHandler(Handlers me) {
        me.add(new StaticResourceHandler());
    }

}
